package com.notify;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.TimerTask;
import java.util.Timer;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.app.ListActivity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;

import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class NotifierActivity extends ListActivity {

	TimerTask scanTask;
	final Handler handler = new Handler();
	Timer t = new Timer();
	ArrayList<HashMap<String, String>> menuItems;

	private ProgressDialog pDialog;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_main);

		scanTask = new TimerTask() {
			public void run() {
				handler.post(new Runnable() {
					public void run() {
						CheckMessages();
					}
				});
			}
		};

		t.schedule(scanTask, 300, 10000);

		new LoadMessages().execute();

		/* END LIST VIEW */
	}

	// Notification Function
	void Notification(String notificationTitle, String notificationMessage,
			String id) {
		int idMessage = Integer.parseInt(id);
		NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		Notification notification = new Notification(
				android.R.drawable.stat_notify_sync, "A New Message!",
				System.currentTimeMillis());
		Intent notificationIntent = new Intent(this, MainActivity.class);
		PendingIntent pendingIntent = PendingIntent.getActivity(this, 1,
				notificationIntent, 0);
		notificationIntent.putExtra("taskId", idMessage);
		notification.setLatestEventInfo(this, notificationTitle,
				notificationMessage, pendingIntent);
		notificationManager.notify(idMessage, notification);
	}

	public void CheckMessages() {

		try {

			XMLParser parser = new XMLParser();

			NodeList nl = new LoadMessages().getMessages(true);

			int count = nl.getLength();

			for (int i = 0; i < count; i++) {

				Element e = (Element) nl.item(i);
				String id = parser.getValue(e,
						getResources().getString(R.string.key_id));
				String name = parser.getValue(e,
						getResources().getString(R.string.key_title));
				String desc = parser.getValue(e,
						getResources().getString(R.string.key_content));

				// Log.v("LOGIN", "ID MESSAGE:" + id);

				Notification(name, desc, id);
			}

			if (count > 0)
				new LoadMessages().execute();

		} catch (Exception e) {

		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.main_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.btConfig:
			Intent in = new Intent(getApplicationContext(), LoginActivity.class);
			finish();
			startActivity(in);
			return true;
		case R.id.update:
			new LoadMessages().execute();
			return true;
		case R.id.close:
			System.exit(0);
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	/* Menu */
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		menu.setHeaderTitle("Delete ?");
		menu.add(0, v.getId(), 0, "Yes");
		menu.add(0, v.getId(), 0, "No");

	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
				.getMenuInfo();
		@SuppressWarnings("unchecked")
		Map<String, String> data = (Map<String, String>) getListView()
				.getItemAtPosition(info.position);

		if (item.getTitle() == "Yes") {

			Log.v("deleting", data.get("id"));

			new ViewActivity().deleteNotify(data.get("id"),
					getApplicationContext());

			Toast.makeText(getApplicationContext(), "Deleted",
					Toast.LENGTH_SHORT).show();

			new LoadMessages().execute();

			return true;
		}

		return super.onContextItemSelected(item);
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {

		TextView idView = (TextView) v.findViewById(R.id.id);
		TextView titleView = (TextView) v.findViewById(R.id.title);
		TextView contentView = (TextView) v.findViewById(R.id.content);

		String ids = idView.getText().toString();
		String title = titleView.getText().toString();
		String content = contentView.getText().toString();

		Intent in = new Intent(getApplicationContext(), ViewActivity.class);

		in.putExtra("id", ids);
		in.putExtra("title", title);
		in.putExtra("content", content);

		startActivity(in);
	}

	class LoadMessages extends AsyncTask<String, String, String> {

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(NotifierActivity.this);
			pDialog.setMessage("Loading...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		@Override
		protected String doInBackground(String... arg0) {

			try {

				menuItems = updateMessajes();

			} catch (Exception e) {
				t.cancel();
				Intent in = new Intent(getApplicationContext(),
						LoginActivity.class);
				finish();
				startActivity(in);
				Toast.makeText(getApplicationContext(),
						"Notify error getting messages " + e.getMessage(),
						Toast.LENGTH_LONG).show();
			}
			return null;
		}

		protected void onPostExecute(String file_url) {
			pDialog.dismiss();
			// updating UI from Background Thread

			runOnUiThread(new Runnable() {
				public void run() {
					ListAdapter adapter = new SimpleAdapter(
							NotifierActivity.this, menuItems,
							R.layout.list_item, new String[] { "id", "title",
									"content" }, new int[] { R.id.id,
									R.id.title, R.id.content });
					// updating listView
					setListAdapter(adapter);
					ListView listView = getListView();
					registerForContextMenu(listView);
				}
			});

		}

		public ArrayList<HashMap<String, String>> updateMessajes() {
			menuItems = new ArrayList<HashMap<String, String>>();

			XMLParser parser = new XMLParser();

			NodeList nl = this.getMessages(false);

			int count = nl.getLength();

			for (int i = 0; i < count; i++) {

				Element e = (Element) nl.item(i);

				String id = parser.getValue(e,
						getResources().getString(R.string.key_id));
				String title = parser.getValue(e,
						getResources().getString(R.string.key_title));
				String desc = parser.getValue(e,
						getResources().getString(R.string.key_content));

				HashMap<String, String> map = new HashMap<String, String>();

				map.put(getResources().getString(R.string.key_id), id);
				map.put(getResources().getString(R.string.key_title),
						title.trim());
				map.put(getResources().getString(R.string.key_content),
						desc.trim());

				menuItems.add(map);
			}
			return menuItems;

		}

		public NodeList getMessages(Boolean news) {
			Tools tools = new Tools();
			String username = tools.getData(getApplicationContext(),
					getResources().getString(R.string.username), "");
			String password = tools.getData(getApplicationContext(),
					getResources().getString(R.string.password), "");
			String server = tools.getData(getApplicationContext(),
					getResources().getString(R.string.server), "");

			try {

				XMLParser parser = new XMLParser();
				String fullUrl = server + "?action=getMessage&username="
						+ username + "&password=" + password + "&news=" + news;

				Log.v("URL", fullUrl);

				String xml = parser.getXmlFromUrl(fullUrl); // getting XML

				Document doc = parser.getDomElement(xml); // getting DOM element

				NodeList nl = doc.getElementsByTagName(getResources()
						.getString(R.string.key_item));
				return nl;

			} catch (Exception e) {

			}
			return null;

		}
	}
}